package c2.cross.business.ladder.rank;

import c2.cross.business.CrossBody;
import cate.common.table.pvp.ladder.LadderRobotRow;
import cate.game.play.part.PlaySide;
import easy.java.practice.errorcode.EcException;
import easy.java.practice.errorcode.EcResult;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/** 天梯赛机器人PlaySide池 */
@Slf4j
public class LadderRobotPlaySidePool {

    private static List<PlaySide> pool = new ArrayList<>();

    private static boolean inited = false;

    public static int size = 0;

    public synchronized static void init(CrossBody context) {
        if(inited) {
            return;
        }
        for(LadderRobotRow robotRow : context.table.ladder.robot.list) {
            EcResult<PlaySide> r_ps = context.play.sideBuilder.createPlaySideByCode(robotRow.instance);
            if(!r_ps.ok()) {
                log.error("天梯赛构建机器人失败:{}, id:{}, 实例配置:{}", r_ps.message, robotRow.id, robotRow.instance);
                continue;
            }
            r_ps.data.snapshot.base.power = robotRow.power;
            pool.add(r_ps.data);
        }
        size = pool.size();
        if(size == 0) {
            throw new EcException("天梯赛机器人列表配置为空，请检查excel配表");
        }
        inited = true;
    }

    /** 通过排名转化robotPsId
     * @param rankNo 从1开始 */
    public static int getRobotPsIdByRankNo(int rankNo) {
        int idx = (rankNo-1) % size;
        return idx;
    }

    public static long getRobotPowerByPsId(int psId) {
        try {
            return getRobotPs(psId).snapshot.base.power;
        } catch (Exception e) {
            log.error("", e);
            return -123;
        }
    }

    public static PlaySide getRobotPs(int psId) {
        if(psId >= pool.size()) {
            log.error("查询天梯赛机器人战力越界 poolSize={} 而psId={}", pool.size(), psId);
        }
        return pool.get(psId).copy();
    }

}
